import { queryLogin, queryAliPayAppAuthTokenBYCode } from '@/core/api';
import type { Response } from '@/core/models';
import { UserToken } from '@/core/consts';
import { useUserInfoStore } from '@/core/store';

/**
 * 登录获取code
 * @param callback 把获取的code返回
 */
export const loginGetCode = (callback : Function) => {
	// #ifdef MP-WEIXIN
	uni.login({
		success: (res : any) => {
			if (res.code) {
				return callback(res.code)
			} else {
				uni.showToast({
					title: '未取得code，请重试',
					duration: 2000,
					icon: 'none'
				});
			}
		},
		fail: (res : any) => {
		}
	})
	// #endif

	// #ifdef MP-ALIPAY
	my.getAuthCode({
		scopes: 'auth_user',
		success: (res : any) => {
			return callback(res.authCode)
		}
	});
	// #endif
}

/** 微信支付宝获取token */
export const handleLoginGetToken = () => {
	return new Promise((resolve) => {
		// 获取 用户数据
		const userInfoStore  = useUserInfoStore();

		loginGetCode(async (code : string) => {
			// #ifdef MP-WEIXIN
			const login : Response<any> = await queryLogin({ code, });
			// #endif

			// #ifdef MP-ALIPAY
			const login : Response<any> = await queryAliPayAppAuthTokenBYCode({ code, });
			// #endif

			if (login.status) {
				if (login.data.auth) {
					uni.setStorageSync(UserToken, login.data.auth.token);
				}
				if (login.data.user) {
					userInfoStore.setUserInfo(login.data.user);
				}
				resolve(login.data)
			} else {
				uni.showToast({
					title: login.msg,
					duration: 2000,
					icon: 'none'
				});
			}
		})
	})

}